// src/pages/article/index.tsx
import React, { useRef, useState, useEffect, useCallback } from "react"
import GeekIcon from "@shared/geekIcon";
import { Skeleton } from "antd-mobile";
import styles from "@pages/article/styles/styles.module.less";
import { useRequestArticleQuery } from "@service/article";
import { useParams } from "react-router-dom";
import dayjs from "dayjs";
import localizedFormat from "dayjs/plugin/localizedFormat";
import "highlight.js/styles/atom-one-dark.css";

import Follow from "./widgets/index";
import Collect from "./widgets/collect/index";
import Favourite from "./widgets/favourite/index";
import { commentSelectors } from "@slice/comment";
import { useDispatch } from "react-redux"; // 导入 useDispatch
import { saveComments } from "@slice/comment"; // 假设这是保存评论的 action
import { useSelector } from "react-redux";
import { useRequestCommentsMutation } from "@store/service/comment";
dayjs.extend(localizedFormat);
// import { access } from "fs/promises";
export default function Article() {
    const id = useParams<{ id: string }>().id!;
    // 发送请求获取文章详情
    const { data, isLoading, isSuccess } = useRequestArticleQuery(id);
    //头部信息的显示隐藏
    const topRef = useRef<HTMLDivElement | null>(null);
    // 获取滚动区域元素
    const articleRef = useRef<HTMLDivElement | null>(null);
    // 用于控制头部作者信息的显示和隐藏
    const [show, setShow] = useState(false);
  
    // 检测文章是否获取成功
    useEffect(() => {
      // 如果文章内容没有获取成功, 阻止程序继续运行
      if (!isSuccess) return;
      // 获取滚动区域DOM对象
      const articleElm = articleRef.current!;
      // 获取文章内容区域上面的区域DOM对象
      const topElm = topRef.current!;
      // 滚动事件的事件处理函数
      const scrollHandler = () => {
        // 如果滚动距离大于了内容区域上面元素的高度
        setShow(articleElm.scrollTop > topElm.offsetHeight);
      };
      // 为滚动区域添加滚动事件
      articleElm.addEventListener("scroll", scrollHandler);
      // 清理驱动区域的滚动事件
      return () => articleElm.removeEventListener("scroll", scrollHandler);
    }, [isSuccess]);
    //切换效果
    const [showComment, setShowComment] = useState(false);
    // 用于获取评论元素对象
    const commentRef = useRef<HTMLDivElement | null>(null);
    useEffect(() => {
        // 显式评论区域
        if (showComment) {
          articleRef.current!.scrollTo({
            top: commentRef.current?.offsetTop,
            behavior: "smooth",
          });
        } else {
          // 显示内容区域
          articleRef.current!.scrollTo({ top: 0, behavior: "smooth" });
        }
      }, [showComment]);


      const dispatch = useDispatch();
      const [offset, setOffset] = useState<string | undefined>();
      // 是否有更多评论可以加载
      const [hasMore, setHasMore] = useState(true);
      // 发送请求获取评论列表
      const [requestComments, { data: comments }] = useRequestCommentsMutation();
    
      // 获取评论列表数据
      const allComments = useSelector(commentSelectors.selectAll);
    
      // 用于加载评论列表
      const loadMore = useCallback(() => {
        return requestComments({type: "a", source: id, limit: 10, offset})
          .unwrap()
          .then((response:any) => {
            // 保存评论列表
            dispatch(saveComments(response.data.results));
            // 如果不两者相等说明没有更多数据可以加载
            setHasMore(response.data.end_id !== response.data.last_id);
            // 设置分页偏移量
            setOffset(response.data.last_id);
          });
      }, [dispatch, id, offset, requestComments]);
      
  return (
    <>
    <div className={styles.header}>
        <div className={styles.left}>
          {show && isSuccess && (
            <div className={styles.center}>
              <img src={data?.data.aut_photo} alt="" />
              <span>{data?.data.aut_name}</span>
              <button>关注</button>
            </div>
          )}
        </div>
        <div ref={articleRef} className={styles.article}>
            <div ref={topRef}>
                <h2 className={styles.title}></h2>
                <div className={styles.meta}></div>
                <div className={styles.author}></div>
            </div>
        </div>
    </div>
    <div className={styles.article}>
      {isLoading && (
        <div className={styles.skeleton}>
          <Skeleton.Paragraph lineCount={2} animated />
          <Skeleton.Paragraph lineCount={3} animated />
          <Skeleton.Paragraph lineCount={5} animated />
          <Skeleton.Paragraph lineCount={2} animated />
          <Skeleton.Paragraph lineCount={4} animated />
        </div>
      )}
      {isSuccess && (
        <>
        <h2 className={styles.title}>{data.data.title}</h2>
        <div className={styles.meta}>
          <span>
            {dayjs(data.data.pubdate).locale("zh-cn").format("LL")}
          </span>
          <span>{data.data.read_count} 阅读</span>
          <span>{data.data.comm_count} 评论</span>
        </div>
        <div className={styles.author}>
          <div className={styles.avatar}>
            <img src={data.data.aut_photo} alt="" />
            <span>{data.data.aut_name}</span>
          </div>
          <div className={styles.follow}>
            <button>关注</button>
          </div>
        </div>
        <div className={styles.content}>112
          <div
            dangerouslySetInnerHTML={{ __html: data.data.content }}
            ></div>
          <div className={styles.footnote}>
            文章发布于：
            {dayjs(data.data.pubdate).locale("zh-cn").format("LL")}
          </div>
        </div>
        </>
      )}
            <div ref={articleRef} className={styles.article}>
                <div className={styles.comment} ref={commentRef}></div>
            </div>
            <div className={styles.bar}>
                <div className={styles.icons}>
                <div className={styles.item} onClick={() => setShowComment((show) => !show)}>
                    <GeekIcon type={"iconbtn_comment"} />
                    <span>评论</span>
                </div>
                </div>
            </div>
    </div>
    <Follow isFollow={data?.data.is_followed} userId={data?.data.aut_id} />
    <Collect isCollect={data?.data.is_collected} id={data?.data.art_id} />
    <Favourite id={data?.data.art_id} isFavourite={data?.data.attitude === 1} />

    </>
  );
}
